package com.pqc.tbk.service.account;

import java.util.Random;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pqc.tbk.dao.user.UserDao;
import com.pqc.tbk.entity.ConstProp;
import com.pqc.tbk.entity.account.User;
import com.pqc.tbk.service.TBKServiceException;
import com.pqc.tbk.utils.Digest;
import com.pqc.tbk.utils.MSGSender;
import com.pqc.tbk.utils.StringUtil;
import com.pqc.tbk.utils.UserUtil;

@Service("userService")
@Transactional(readOnly = false)
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;
	private final Random rd = new Random();
	private final Logger logger = Logger.getLogger(UserServiceImpl.class);

	@Override
	public void delete(final User user) {
		userDao.delete(user);
	}

	@Override
	@Transactional(readOnly = false)
	public void update(final User user) {
		userDao.update(user);
	}

	@Override
	@Transactional(readOnly = true)
	public User checkLogin(final String username, String password) {
		final User user = userDao.findByUsername(username);
		if (user == null) {
			return null;
		}
		password = Digest.md5(password);
		if (user.getPassword().equals(password)) {
			return user;
		} else {
			return null;
		}
	}

	@Override
	@Transactional(readOnly = true)
	public boolean exist(final String username) {
		return null != userDao.findByUsername(username);
	}

	@Override
	@Transactional(readOnly = true)
	public boolean existEmail(final String email) {
		return null != userDao.findByEmail(email);
	}

	@Override
	@Transactional(readOnly = true)
	public User findUser(final Long id) {
		return userDao.findOne(id, User.class);
	}

	@Override
	public boolean updatePwd(String oPwd, String nPwd, final Long id) {
		// 新旧密码一样，修改失败
		if (oPwd.equals(nPwd)) {
			return false;
		}
		final User user = userDao.findOne(id, User.class);
		if (user == null) {
			return false;
		}
		oPwd = Digest.md5(oPwd);
		nPwd = Digest.md5(nPwd);
		// 旧密码错误，不能修改
		if (user.getPassword().equals(oPwd)) {
			user.setPassword(nPwd);
			userDao.save(user);
		} else {
			return false;
		}
		return true;
	}

	@Override
	public boolean updateBasicInfo(final User user, final Long id) {
		final User u = userDao.findOne(id, User.class);
		// 修改信息前需要进行密码校验
		if (u == null) {
			return false;
		}
		final char[] state = u.getState().toCharArray();
		if (u.getPassword().equals(Digest.md5(user.getPassword())) == false) {
			return false;
		}
		if (!StringUtil.isEmptyOrNull(user.getEmail())) {
			// if (user.getEmail().equals(u.getEmail()) == false) {
			if (!existEmail(user.getEmail())) {// 不存在这样的email，即也不会和原来的相同
				u.setEmail(user.getEmail());
				state[1] = '0';// 更改邮箱需要重新绑定
			}

		}
		if (!StringUtil.isEmptyOrNull(user.getQq())) {
			u.setQq(user.getQq());
		}
		if (!StringUtil.isEmptyOrNull(user.getSchool())) {
			u.setSchool(user.getSchool());
		}
		u.setSex(user.getSex());
		if (!StringUtil.isEmptyOrNull(user.getNick())) {
			u.setNick(user.getNick());
		} else {
			u.setNick(u.getUsername());
		}
		u.setState(new String(state));
		userDao.update(u);
		return true;
	}

	/**
	 * 1--》验证成功 2--》非法参数 3--》链接失效 4--》重复绑定
	 */
	@Override
	public int emailVerify(final String email, final Long t, final String sign) {
		if (Digest.sha1(email + t, null).equals(sign) == false) {
			return 2;
		}
		final Long now = System.currentTimeMillis();
		if ((now - t) > (24L * 60 * 60 * 1000)) {
			return 3;
		}
		final User user = userDao.findByEmail(email);
		final char[] state = user.getState().toCharArray();
		if (state[1] == '1') {
			return 4;
		}
		state[1] = '1';// 标记email状态为绑定
		user.setState(new String(state));
		userDao.update(user);
		return 1;
	}

	@Override
	@Transactional(readOnly = true)
	public User findByUserName(final String username) {
		return userDao.findByUsername(username);
	}

	@Override
	public void regist(final User user, final String inviter) {
		if (userDao.findByUsername(user.getUsername()) != null) {
			logger.info("ERROR:尝试添加已存在的用户");
			throw new TBKServiceException("ERROR:尝试添加已存在的用户");
		}
		Long inviter_id = 0L;
		try {
			inviter_id = Long.parseLong(inviter);
		}
		catch (final NumberFormatException e) {
			inviter_id = 0L;
		}
		final User user_inviter = userDao.findOne(inviter_id, User.class);
		if (user_inviter != null) {
			user.setInviter_id(inviter_id);
			if (user_inviter.getUsed_amount() >= user_inviter.getMax_amount()) {
				logger.info("ERROR:" + user_inviter.getUsername()
						+ ",您的推广数量已满,请选择充值。");
				throw new TBKServiceException("ERROR:您的推广数量已满,请选择充值。");
			} else {
				user_inviter.setUsed_amount(user_inviter.getUsed_amount() + 1);
			}
		}

		user.setPassword(Digest.md5(user.getPassword()));
		if ((user.getNick() == null) || "".equals(user.getNick())) {
			user.setNick(user.getUsername());
		}
		// 初始化其他信息
		user.setMoney(0.0);
		user.setScore(0L);
		user.setMoney_rest(0.0);
		// user.setState("1000");
		// 自己注册的 || 推广者为无效用户 || 推广者为第四层次
		if ((user_inviter == null) || (user_inviter.getUserActive() == false)
				|| (user_inviter.getLevel() == 4)) {
			user.setState("0000");
			user.setLevel(ConstProp.Promote.INVALID_LEVEL);
			user.setMax_amount(ConstProp.Promote.UNLIMITED_AMOUNT);
		} else {
			user.setState("1000");
			user.setLevel(user_inviter.getLevel() + 1);
			user.setMax_amount(getAmount(user_inviter.getLevel()));
		}
		user.setUsed_amount(0);
		userDao.save(user);
	}

	public int getAmount(final int inviter_level) {
		if (inviter_level == 0) {
			return ConstProp.Promote.FIRST_AMOUNT;
		} else if (inviter_level == 1) {
			return ConstProp.Promote.SECOND_AMOUNT;
		} else if (inviter_level == 2) {
			return ConstProp.Promote.THIRD_AMOUNT;
		} else if (inviter_level == 3) {
			return ConstProp.Promote.UNLIMITED_AMOUNT;
		} else {
			return 0;
		}
	}

	@Override
	@Transactional(readOnly = true)
	public int countByTel(final String tel) {
		return userDao.countByTel(tel);
	}

	@Override
	@Transactional(readOnly = true)
	public int countByAlipay(final String alipay) {
		return userDao.countByAlipay(alipay);
	}

	@Override
	public void bindTel(final String tel) {
		// 获取用户
		final User user = findUser(UserUtil.getUID());
		// 设置电话
		user.setTel(tel);
		// 设置电话激活状态
		final StringBuilder sb = new StringBuilder(user.getState().toString());
		sb.replace(ConstProp.UserStatePos.TEL, ConstProp.UserStatePos.TEL + 1,
				"1");
		user.setState(sb.toString());
		// 更新用户
		userDao.update(user);
	}

	@Override
	public void bindAlipay(final String alipay) {
		// 获取用户
		final User user = findUser(UserUtil.getUID());
		// 设置支付宝
		user.setAlipay(alipay);
		// 设置支付宝激活状态
		final StringBuilder sb = new StringBuilder(user.getState().toString());
		sb.replace(ConstProp.UserStatePos.ALIPAY,
				ConstProp.UserStatePos.ALIPAY + 1, "1");
		user.setState(sb.toString());
		// 更新用户
		userDao.update(user);
	}

	@Override
	public String sendMsg(final String mobile) throws Exception {
		final StringBuilder sb = new StringBuilder();
		for (int i = 0; i < 6; i++) {
			final int n = rd.nextInt(10);
			sb.append(n);
		}
		final String msg = ConstProp.SendContent.SEND_BIND_TEL_CODE
				+ sb.toString() + ConstProp.SendContent.COMMON_END;
		MSGSender.sendMessage(mobile, msg);
		logger.info(msg);
		return sb.toString();
	}

	@Override
	public User findByEmail(final String email) {
		return userDao.findByEmail(email);
	}

}
